import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_oauth.dart';
import 'package:ceramics/model/ab_singleton.dart';
import 'package:ceramics/model/ab_works.dart';
import 'package:ceramics/pages/main/home/ab_right_top_hollow_canvas.dart';
import 'package:ceramics/pages/main/hot/ab_hot_works_item.dart';
import 'package:ceramics/styles/ab_styles.dart';
import 'package:ceramics/util/ab_api.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/widgets/ab_elevate_button.dart';
import 'package:ceramics/widgets/ab_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'ab_home_detail_page.dart';

class ABUserWorksPage extends StatefulWidget {
  final ABUser user;
  const ABUserWorksPage({super.key, required this.user});

  @override
  State<ABUserWorksPage> createState() => _ABUserWorksPageState();
}

class _ABUserWorksPageState extends State<ABUserWorksPage> {
  var works = <ABWorks>[];

  @override
  void initState() {
    super.initState();
    _fetchWorks();
  }

  _fetchWorks() async {
    works = await ABWorks.worksWithUserId(widget.user.userId);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        backgroundColor: const Color(0x00FFFFFF),
      ),
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/ceramics_39.webp"),
            fit: BoxFit.cover,
          ),
        ),
        width: double.infinity,
        child: Stack(
          children: [
            SafeArea(
              bottom: false,
              child: LayoutBuilder(builder: (context, constraints) {
                return ListView(
                  children: [
                    _buildInfoRow(),
                    ABRightTopHollowCanvas(
                        child: ListView.separated(
                      itemBuilder: (ctx, idx) {
                        var model = works[idx];
                        return ABHotWorksItem(works: model).onTap(() {
                          Get.to(
                              () => ABHomeDetailPage(id: model.id.toString()),
                              arguments: model);
                        }).paddingOnly(top: 30);
                      },
                      separatorBuilder: (ctx, idx) {
                        return 10.toVerticalBox;
                      },
                      itemCount: works.length,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      padding: const EdgeInsets.symmetric(
                          horizontal: 20, vertical: 10),
                    )).minHeight(constraints.maxHeight)
                  ],
                );
              }),
            ),
            if (widget.user.userId != ABSingleton.user?.userId)
              Positioned(
                  left: 50,
                  right: 50,
                  bottom: 80,
                  child: Obx(() {
                    return ABSingleton.didFollow(widget.user.userId)
                        ? ElevatedButton(
                            onPressed: _follow,
                            style: ElevatedButton.styleFrom(backgroundColor: Colors.black.withOpacity(0.5)),
                            child: const Text(
                              'Unfollow',
                              style: ABStyles.tsWhite20R,
                            ))
                        : ABElevateButton(
                            onPressed: _follow,
                            child: const Text('Follow ＋',
                                style: ABStyles.tsWhite20R));
                  }).maxHeight(50))
          ],
        ),
      ),
    );
  }

  Row _buildInfoRow() {
    return Row(
      children: [
        20.toHorizontalBox,
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(widget.user.nickname),
            8.toVerticalBox,
            Container(
                decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    borderRadius: BorderRadius.circular(5)),
                padding:
                    const EdgeInsets.symmetric(horizontal: 10, vertical: 3),
                child: Text('ID: ${widget.user.userId.substring(12)}',
                    style: ABStyles.tsWhite14))
          ],
        ),
        const Spacer(),
        Transform(
            transform: Matrix4.translationValues(0, 30, 0),
            child: ABCircleAvatar(url: widget.user.avatar, size: 80)),
        20.toHorizontalBox
      ],
    );
  }

  void _follow() async {
    var userId = widget.user.userId;
    if (ABSingleton.didFollow(userId)) {
      await api.unfollow(userId);
      ABSingleton.follows.removeWhere((element) => element.userId == userId);
      toast('Unfollow Success');
    } else {
      await api.follow(userId);
      await ABSingleton.updateFollows();
      toast('Follow Success');
    }
    Get.find<ABHomeDetailController>().update();
    setState(() {});
  }
}
